<template>
	<div>
	    <div class="photo-cube" style="text-align:center;">
	        <div style="margin-top:20px;" v-on:click="photograph">
	            <f7-icon f7="camera"></f7-icon><br/>
	            <span>拍照</span>
	        </div>
	    </div>
	    <div v-for="(photo, i) in showPhotos" class="photo-cube" 
	        style="border:0; margin-top:0px; position:relative;">
	        <div style="position:absolute; left:55px; top:0px; color:red;"
	            @click="photoDelete(i)">
	            <f7-icon f7="close_round_fill"></f7-icon>
	        </div>
	        <div class="photo-cube"
	            style="background-size:80px 80px; background-repeat:no-repeat;"
	            :style="{'background-image':'url(' + photo + ')'}"
	            @click="$refs.photoBrowser.open(i)">
	        </div>
	    </div>
        <f7-photo-browser ref="photoBrowser" type="popup" back-link-text="关闭"></f7-photo-browser>
        <f7-popup :id="uuid + '-editPhotoPopup'" :backdrop="false" :close-by-backdrop-click="false">
            <f7-page>
                <f7-navbar>
                    <f7-nav-left>
                        <f7-link href="#" @click="cancel">取消</f7-link>
                    </f7-nav-left>
                    <f7-nav-title title="编辑照片"></f7-nav-title>
                    <f7-nav-right>
                        <f7-link href="#" @click="revoke">撤销</f7-link>
                        <f7-link href="#" @click="save">保存</f7-link>
                    </f7-nav-right>
                </f7-navbar>
                <canvas :id="uuid + '-editPhotoCanvas'" width="600" height="800"
                    style="width:95%; height:95%; border:1px solid black; margin-left:5px; margin-top:10px;">
                </canvas>
                <f7-fab href="#" @click="addText" position="left-bottom">
                	<f7-icon material="text_format"></f7-icon>
                </f7-fab>
                <div class="item-input-wrap" :id="uuid + '-inputFont'" name="description" 
                	style="display:none;position:absolute;left:100Px;top:100Px;z-index:1000;;
                	width:200px;height:25px;">
		            <input type="text" name="description" style="width:50%;height:100%;float:left;color:red;border: 1px solid #eeeeee">
				    <f7-button fill @click="cancelFont" color="red" style="width:25%;height:100%;float:left;line-height:25px;">取消</f7-button>
				    <f7-button fill @click="defineFont" color="blue" style="width:25%;height:100%;float:left;line-height:25px;">确定</f7-button>
				</div>
            </f7-page>
        </f7-popup>
	</div>
</template>

<script>
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import FileUtil from "@/utils/FileUtil.js";
import $ from 'jquery';
import { getUser, setUser, clearUser } from '@/utils/auth';
import { getStore, setStore, clearStore } from '@/utils/storage';
import keys from '@/utils/rememberKeys';

export default {
    data: function() {
        return {
        	uuid: Common.uuid(),
        	photos: [],
        	tempPhotos: [],
        	eventPosition: {},
        	toastTop: {},
        	showPhotos: []
        };
    },
    methods: {
    	addPhotos: function(photos) {
    		this.photos = this.photos.concat(photos.concat());
    	},
    	photograph: function() {
    		var self = this;
    		if(this.photos.length < 3) {
    			window.navigator.camera.getPicture(function(imageData) {
                    self.$f7.preloader.show();
                    var image = {};
                    var url = "data:image/jpeg;base64," + imageData;
                    var canvas = document.getElementById(self.uuid + '-editPhotoCanvas');
                    var ctx = canvas.getContext('2d');
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    var img = new Image();
                    img.onload = function() {
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                        ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
                        ctx.fillRect(0, canvas.height - 30 , canvas.width, canvas.height);
                        ctx.font="bold 20px Arial";
                        ctx.fillStyle = "#EEEEEE";
                        var text = getUser().realname;
                        text += DateUtil.dateToStr('yyyy-MM-dd hh:mm', new Date());
                        text += ' 拍摄';
                        ctx.fillText(text, canvas.width - 300, canvas.height - 5);
                        self.saveTempPhoto();
                        self.$f7.popup.open('#' + self.uuid + '-editPhotoPopup', true);
                        self.$f7.preloader.hide();
                    }
                    img.src = url;
    			}, function(message) {
    			    console.error(message);
    			    self.$f7.dialog.alert('', '拍照失败');
    			}, {
                    quality: 50,
                    destinationType: window.parent.Camera.DestinationType.DATA_URL,
                    correctOrientation: true
                });
    		} else {
    			this.$f7.dialog.alert("一个问题最多只能上传三张照片", "数量超限！");
    		}
    	},
    	cancel: function() {
    		var self = this;
            self.tempPhotos = [];
    		this.$f7.popup.close('#' + self.uuid + '-editPhotoPopup', true);
    	},
    	revoke: function() {
    		if(this.tempPhotos.length > 1) {
    			var self = this;
    			self.$f7.preloader.show();
    			new Promise((resolve, reject) => {
    				let path = self.tempPhotos[self.tempPhotos.length - 2];
    				window.resolveLocalFileSystemURL(path, fileEntry => {
    					fileEntry.file(file => {
    						resolve(file.localURL);
    					}, error => {
    						reject(error);
    					})
    				}, error => {
    					reject(error);
    				});
    			}).then((cdvPath) => {
    				var canvas = document.getElementById(self.uuid + '-editPhotoCanvas');
                    var ctx = canvas.getContext('2d');
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    var img = new Image();
                    img.onload = function() {
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                        self.tempPhotos.pop();
                        self.$f7.preloader.hide();
                    }
                    img.src = cdvPath;
    			}).catch((error) => {
    				console.error(error);
    				self.$f7.dialog.alert('', '撤销照片失败');
    				self.$f7.preloader.hide();
    			});
    		}
    	},
    	save: function() {
    		var self = this;
    		var tempPath = this.tempPhotos[this.tempPhotos.length - 1];
            this.tempPhotos = [];
            self.photos.push(tempPath);
            self.$emit('photoAdd', tempPath);
            self.$f7.popup.close('#' + self.uuid + '-editPhotoPopup', true);
    	},
    	photoDelete: function(index) {
    		var self = this;
    		this.$f7.dialog.confirm("", "你确定要删除图片吗？", function() {
                var photo = self.photos[index];
                self.photos.splice(index, 1);
                self.$emit('photoDelete', photo);
            });
    	},
    	saveTempPhoto: function() {
            var self = this;
            var canvas = document.getElementById(self.uuid + '-editPhotoCanvas');
            canvas.toBlob(function(blob) {
                let url = URL.createObjectURL(blob);
                let splits = url.split('/');
                let fileName = splits[splits.length - 1] + '.jpg';
                FileUtil.save(Common.directory().temp, fileName, blob).then(filePath => {
                	self.tempPhotos.push(filePath);
                });
            }, 'image/jpeg', 1);
    	},
    	addText: function() {
    		var self = this;
    		self.toastTop.open();
    		var canvas = document.getElementById(self.uuid + '-editPhotoCanvas');
    		canvas.addEventListener('click', self.openInput, false);
    	},
    	openInput: function(ev) {
    		var self = this;
    		$("#" + this.uuid + "-inputFont").css('display','block');
    		$("#" + this.uuid + "-inputFont button").css('display','block');
    		$("#" + this.uuid + "-inputFont input").focus()
    		var canvas = document.getElementById(self.uuid + '-editPhotoCanvas');
    		self.eventPosition = self.getEventPosition(ev,canvas);
    		canvas.removeEventListener('click', self.openInput, false);
    	},
    	cancelFont: function() {
    		$("#" + this.uuid + "-inputFont").css('display','none');
    		$("#" + this.uuid + "-inputFont input").val("");
    		this.toastTop.close();
    	},
    	defineFont: function() {
    		var self = this;
    		var text = $("#" + this.uuid + "-inputFont input").val();
    		self.drawText(text);
    		$("#" + this.uuid + "-inputFont").css('display','none');
    		$("#" + this.uuid + "-inputFont input").val("");
    		self.saveTempPhoto();
    		self.toastTop.close();
    	},
    	drawText: function(text) {
    		var self = this;
    		var canvas = document.getElementById(self.uuid + '-editPhotoCanvas');
            var ctx = canvas.getContext('2d');
            ctx.font="bold 20px Arial";
            ctx.fillStyle = "red";
            ctx.fillText(text, self.eventPosition.x, self.eventPosition.y);
    	},
    	getEventPosition: function(ev,canvas) {
   		    var x, y;
   		    var box = canvas.getBoundingClientRect();
   	  		var x = (ev.clientX - box.left) * canvas.width / box.width;
   	  		var y = (ev.clientY - box.top) * canvas.height / box.height;
   		    return {x: x, y: y};
   		}
    },
    watch: {
    	'photos': function(newVal, oldVal) {
    		let self = this;
    		self.showPhotos = [];
    		this.photos.forEach(photo => {
                window.resolveLocalFileSystemURL(photo, fileEntry => {
                    fileEntry.file(file => {
                    	self.showPhotos.push(file.localURL);
                    });
                });
    		});
    	},
    	'showPhotos': function(newVal, oldVal) {
    		this.$refs.photoBrowser.f7PhotoBrowser.params.photos = this.showPhotos;
    	}
    },
    mounted: function() {
    	var self = this;
    	self.toastTop = self.$f7.toast.create({
			text: '请在图片上点击对应位置编辑文字',
			position: 'top',
			closeTimeout: 1000 * 60 * 60,
		});
        var canvas = document.getElementById(self.uuid + '-editPhotoCanvas');
        var ctx = canvas.getContext('2d');
        ctx.strokeStyle = "#FF0000";
        ctx.lineWidth = 5;
        var x = 0;
        var y = 0;
        canvas.addEventListener('touchstart', function(event) {
            if(event.touches.length > 0) {
                var box = canvas.getBoundingClientRect();
                var widthCoefficient = canvas.width / box.width;
                var heightCoefficient = canvas.height / box.height;
                var touch = event.touches[0];
                x = (touch.clientX - box.left) * widthCoefficient;
                y = (touch.clientY - box.top) * heightCoefficient;
            }
        }, false);
        canvas.addEventListener('touchmove', function(event) {
            if(event.touches.length > 0) {
                var box = canvas.getBoundingClientRect();
                var widthCoefficient = canvas.width / box.width;
                var heightCoefficient = canvas.height / box.height;
                var touch = event.touches[0];
                ctx.beginPath();
                ctx.moveTo(x, y);
                x = (touch.clientX - box.left) * widthCoefficient;
                y = (touch.clientY - box.top) * heightCoefficient;
                ctx.lineTo(x, y);
                ctx.stroke();
            }
        }, false);
        canvas.addEventListener('touchend', function(event) {
            self.saveTempPhoto();
            x = 0;
            y = 0;
        }, false);
    }
}

</script>

<style scoped>
.photo-cube {
    width:80px;
    height:80px;
    float:left;
    margin-right:5px;
    margin-bottom:5px;
    border: 1px solid #007aff;
}
</style>
